// 状态常量
const STATES = {
  IDLE: 'idle',       // 未启动
  WORKING: 'working',    // 工作
  WORK_END: 'work_end',  // 工作结束
  SOLVED: 'solved',    // 解决
  RESTING: 'resting',    // 休息
  PAUSED: 'paused'     // 暂停
};

// 应用状态 - 从本地存储获取或使用默认值
let workTime = 25 * 60; // 默认25分钟工作（以秒为单位存储）
let restTime = 5 * 60;  // 默认5分钟休息（以秒为单位存储）
let enableNotifications = true; // 是否启用系统通知
let notificationSound = true;   // 通知是否有声音

// 计划相关数据
let plans = JSON.parse(localStorage.getItem('tomatoPlans') || '{}'); // 按日期存储计划
let tags = JSON.parse(localStorage.getItem('tomatoTags') || '[{"id": "1", "name": "学习", "color": "#3498db"}, {"id": "2", "name": "工作", "color": "#2ecc71"}, {"id": "3", "name": "锻炼", "color": "#e74c3c"}]');
let templates = JSON.parse(localStorage.getItem('tomatoTemplates') || '[]');
let currentPlanDate = new Date();
let selectedPlanId = null;

// 应用状态
let currentState = STATES.IDLE;
let backState = STATES.IDLE;
let remainingTime = workTime;
let startTime = null;
let pauseStartTime = null;
let totalPauseTime = 0;
let animationId;
let initialRemaining;
let endTimeoutId; // 用于存储兜底定时器的ID
let targetTime; // 倒计时结束的目标时间戳（毫秒）

// 数据记录
let records = JSON.parse(localStorage.getItem('tomatoRecords') || '[]');
let selectedDate = new Date(); // 当前选中的日期
let currentPeriod = 'day'; // 当前选中的周期
let importData = null; // 临时存储待导入的数据

// DOM元素
const timerDisplay = document.getElementById('timer');
const statusDisplay = document.getElementById('status');
const buttonsContainer = document.getElementById('buttons-container');
const notification = document.getElementById('notification');
const periodOptions = document.querySelectorAll('.period-option');
const periodSelectBtn = document.getElementById('period-select-btn');
const periodDropdown = document.getElementById('period-dropdown');
const selectedPeriodText = document.getElementById('selected-period-text');
const workSessionsEl = document.getElementById('work-sessions');
const totalWorkEl = document.getElementById('total-work');
const totalRestEl = document.getElementById('total-rest');
const totalSolveEl = document.getElementById('total-solve');
const timeChartCanvas = document.getElementById('time-chart');
const datePicker = document.getElementById('date-picker');
const prevPeriodBtn = document.getElementById('prev-period');
const nextPeriodBtn = document.getElementById('next-period');
const clearDataBtn = document.getElementById('clear-data-btn');
const confirmModal = document.getElementById('confirm-modal');
const cancelDeleteBtn = document.getElementById('cancel-delete');
const confirmDeleteBtn = document.getElementById('confirm-delete');
const confirmMessageEl = document.getElementById('confirm-message');
const navItems = document.querySelectorAll('.nav-item');
const interfaces = document.querySelectorAll('.interface');

// 计划界面元素
const planDatePicker = document.getElementById('plan-date-picker');
const planPrevDateBtn = document.getElementById('plan-prev-date');
const planNextDateBtn = document.getElementById('plan-next-date');
const planTableBody = document.getElementById('plan-table-body');
const selectAllPlansCheckbox = document.getElementById('select-all-plans');
const addPlanBtn = document.getElementById('add-plan-btn');
const deletePlanBtn = document.getElementById('delete-plan-btn');
const manageTagsBtn = document.getElementById('manage-tags-btn');
const manageTemplatesBtn = document.getElementById('manage-templates-btn');

// 计划相关模态框元素
const deletePlanModal = document.getElementById('delete-plan-modal');
const cancelDeletePlanBtn = document.getElementById('cancel-delete-plan');
const confirmDeletePlanBtn = document.getElementById('confirm-delete-plan');
const addPlanModal = document.getElementById('add-plan-modal');
const cancelAddPlanBtn = document.getElementById('cancel-add-plan');
const customAddOption = document.getElementById('custom-add-option');
const templateAddOption = document.getElementById('template-add-option');
const templateSelector = document.getElementById('template-selector');

// 标签管理元素
const tagManagementModal = document.getElementById('tag-management-modal');
const tagManagementContainer = document.getElementById('tag-management-container');
const addTagBtn = document.getElementById('add-tag-btn');
const cancelTagManagementBtn = document.getElementById('cancel-tag-management');
const saveTagManagementBtn = document.getElementById('save-tag-management');

// 模板管理元素
const templateManagementModal = document.getElementById('template-management-modal');
const templateManagementContainer = document.getElementById('template-management-container');
const addTemplateBtn = document.getElementById('add-template-btn');
const cancelTemplateManagementBtn = document.getElementById('cancel-template-management');
const saveTemplateManagementBtn = document.getElementById('save-template-management');

// 导入导出相关元素
const exportDataBtn = document.getElementById('export-data-btn');
const importDataBtn = document.getElementById('import-data-btn');
const fileInput = document.getElementById('file-input');
const importConfirmModal = document.getElementById('import-confirm-modal');
const cancelImportBtn = document.getElementById('cancel-import');
const confirmImportBtn = document.getElementById('confirm-import');

// 设置相关元素 — 仅保留分钟输入
const workMinutesInput = document.getElementById('work-minutes');
const restMinutesInput = document.getElementById('rest-minutes');
const enableNotificationsInput = document.getElementById('enable-notifications');
const notificationSoundInput = document.getElementById('notification-sound');
const saveSettingsBtn = document.getElementById('save-settings');

// 初始化
function init() {
  // 加载保存的设置
  loadSettings();
  
  // 设置默认日期为今天
  const today = new Date();
  const dateString = today.toISOString().split('T')[0];
  datePicker.value = dateString;
  planDatePicker.value = dateString;
  selectedDate = today;
  currentPlanDate = today;
  
  // 设置默认选中的周期文本
  selectedPeriodText.textContent = document.querySelector('.period-option.active').textContent;
  
  // 初始化计划表格
  renderPlanTable();
  renderTagManagement();
  renderTemplateManagement();
  renderTemplateSelector();
  
  updateDisplay();
  setupEventListeners();
  requestNotificationPermission();
}

// 设置事件监听器
function setupEventListeners() {
  // 底部导航切换
  navItems.forEach(item => {
    item.addEventListener('click', function() {
      const targetId = this.getAttribute('data-target');
      
      // 更新导航状态
      navItems.forEach(nav => nav.classList.remove('active'));
      this.classList.add('active');
      
      // 显示目标界面
      interfaces.forEach(iface => iface.classList.remove('active'));
      document.getElementById(targetId).classList.add('active');
      
      // 如果切换到数据界面，更新数据显示
      if (targetId === 'data-interface') {
        updateDataDisplay();
      }
    });
  });
  
  // 计划日期选择器事件
  planDatePicker.addEventListener('change', function() {
    currentPlanDate = new Date(this.value);
    renderPlanTable();
  });
  
  // 计划日期导航按钮
  planPrevDateBtn.addEventListener('click', function() {
    currentPlanDate.setDate(currentPlanDate.getDate() - 1);
    planDatePicker.value = currentPlanDate.toISOString().split('T')[0];
    renderPlanTable();
  });
  
  planNextDateBtn.addEventListener('click', function() {
    currentPlanDate.setDate(currentPlanDate.getDate() + 1);
    planDatePicker.value = currentPlanDate.toISOString().split('T')[0];
    renderPlanTable();
  });
  
  // 全选计划
  selectAllPlansCheckbox.addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('.plan-checkbox');
    checkboxes.forEach(checkbox => {
      checkbox.checked = this.checked;
    });
  });
  
  // 计划操作按钮
  addPlanBtn.addEventListener('click', function() {
    renderTemplateSelector();
    addPlanModal.style.display = 'flex';
  });
  
  cancelAddPlanBtn.addEventListener('click', function() {
    addPlanModal.style.display = 'none';
  });
  
  customAddOption.addEventListener('click', function() {
    addNewPlan();
    addPlanModal.style.display = 'none';
  });
  
  deletePlanBtn.addEventListener('click', function() {
    const checkedCount = document.querySelectorAll('.plan-checkbox:checked').length;
    if (checkedCount === 0) {
      showNotification('请先选择要删除的计划', false);
      return;
    }
    deletePlanModal.style.display = 'flex';
  });
  
  cancelDeletePlanBtn.addEventListener('click', function() {
    deletePlanModal.style.display = 'none';
  });
  
  confirmDeletePlanBtn.addEventListener('click', function() {
    deleteSelectedPlans();
    deletePlanModal.style.display = 'none';
  });
  
  // 标签管理
  manageTagsBtn.addEventListener('click', function() {
    renderTagManagement();
    tagManagementModal.style.display = 'flex';
  });
  
  cancelTagManagementBtn.addEventListener('click', function() {
    tagManagementModal.style.display = 'none';
  });
  
  saveTagManagementBtn.addEventListener('click', function() {
    saveTagManagement();
    tagManagementModal.style.display = 'none';
    renderPlanTable(); // 更新计划表格中的标签选择器
    showNotification('标签已保存', false);
  });
  
  addTagBtn.addEventListener('click', function() {
    addNewTag();
  });
  
  // 模板管理
  manageTemplatesBtn.addEventListener('click', function() {
    renderTemplateManagement();
    templateManagementModal.style.display = 'flex';
  });
  
  cancelTemplateManagementBtn.addEventListener('click', function() {
    templateManagementModal.style.display = 'none';
  });
  
  saveTemplateManagementBtn.addEventListener('click', function() {
    saveTemplateManagement();
    templateManagementModal.style.display = 'none';
    renderTemplateSelector();
    showNotification('模板已保存', false);
  });
  
  addTemplateBtn.addEventListener('click', function() {
    addNewTemplate();
  });
  
  saveSettingsBtn.addEventListener('click', saveSettings);
  
  // 周期选择下拉菜单
  periodSelectBtn.addEventListener('click', function() {
    periodDropdown.classList.toggle('show');
    this.classList.toggle('open');
  });
  
  // 点击其他地方关闭下拉菜单
  document.addEventListener('click', function(event) {
    if (!periodSelectBtn.contains(event.target) && !periodDropdown.contains(event.target)) {
      periodDropdown.classList.remove('show');
      periodSelectBtn.classList.remove('open');
    }
  });
  
  // 周期选项点击事件
  periodOptions.forEach(option => {
    option.addEventListener('click', function() {
      const period = this.getAttribute('data-period');
      
      // 更新选中状态
      periodOptions.forEach(opt => opt.classList.remove('active'));
      this.classList.add('active');
      
      // 更新显示文本
      selectedPeriodText.textContent = this.textContent;
      
      // 更新当前周期
      currentPeriod = period;
      
      // 关闭下拉菜单
      periodDropdown.classList.remove('show');
      periodSelectBtn.classList.remove('open');
      
      // 更新数据显示
      updateDataDisplay();
    });
  });
  
  // 日期选择器事件
  datePicker.addEventListener('change', function() {
    selectedDate = new Date(this.value);
    updateDataDisplay();
  });
  
  // 上一周期/下一周期按钮事件
  prevPeriodBtn.addEventListener('click', function() {
    navigatePeriod(-1);
  });
  
  nextPeriodBtn.addEventListener('click', function() {
    navigatePeriod(1);
  });
  
  // 清除数据相关事件
  clearDataBtn.addEventListener('click', showClearConfirmation);
  cancelDeleteBtn.addEventListener('click', hideClearConfirmation);
  confirmDeleteBtn.addEventListener('click', clearSelectedData);
  
  // 为清除范围选项添加事件监听
  document.querySelectorAll('input[name="clearScope"]').forEach(radio => {
    radio.addEventListener('change', updateClearConfirmationMessage);
  });
  
  // 导入导出相关事件
  exportDataBtn.addEventListener('click', exportAllData);
  importDataBtn.addEventListener('click', () => fileInput.click());
  fileInput.addEventListener('change', handleFileImport);
  cancelImportBtn.addEventListener('click', hideImportConfirmation);
  confirmImportBtn.addEventListener('click', confirmDataImport);
  
  // 初始化拖放功能
  initDragAndDrop();
}

// 初始化拖放功能
function initDragAndDrop() {
  const tableBody = document.getElementById('plan-table-body');
  let draggedItem = null;
  
  tableBody.addEventListener('dragstart', function(e) {
    if (e.target.closest('tr') && !e.target.closest('tr').classList.contains('header')) {
      draggedItem = e.target.closest('tr');
      setTimeout(() => {
        draggedItem.classList.add('dragging');
      }, 0);
    }
  });
  
  tableBody.addEventListener('dragend', function() {
    if (draggedItem) {
      draggedItem.classList.remove('dragging');
      draggedItem = null;
      // 保存新的排序
      savePlanOrder();
    }
  });
  
  tableBody.addEventListener('dragover', function(e) {
    e.preventDefault();
    const afterElement = getDragAfterElement(tableBody, e.clientY);
    const draggable = document.querySelector('.dragging');
    if (afterElement == null) {
      tableBody.appendChild(draggable);
    } else {
      tableBody.insertBefore(draggable, afterElement);
    }
  });
}

// 获取拖拽后应该放置的位置
function getDragAfterElement(container, y) {
  const draggableElements = [...container.querySelectorAll('tr:not(.dragging):not(.header)')];
  
  return draggableElements.reduce((closest, child) => {
    const box = child.getBoundingClientRect();
    const offset = y - box.top - box.height / 2;
    if (offset < 0 && offset > closest.offset) {
      return { offset: offset, element: child };
    } else {
      return closest;
    }
  }, { offset: Number.NEGATIVE_INFINITY }).element;
}

// 保存计划顺序
function savePlanOrder() {
  const dateKey = getDateKey(currentPlanDate);
  if (!plans[dateKey]) return;
  
  const rows = document.querySelectorAll('#plan-table-body tr:not(.header)');
  const orderedIds = Array.from(rows).map(row => row.getAttribute('data-id'));
  
  // 重新排序计划
  const orderedPlans = orderedIds.map(id => plans[dateKey].find(plan => plan.id === id));
  plans[dateKey] = orderedPlans;
  
  // 保存到本地存储
  localStorage.setItem('tomatoPlans', JSON.stringify(plans));
  
  // 重新渲染表格以更新编号
  renderPlanTable();
}

// 渲染计划表格
function renderPlanTable() {
  const dateKey = getDateKey(currentPlanDate);
  const datePlans = plans[dateKey] || [];
  
  planTableBody.innerHTML = '';
  
  datePlans.forEach((plan, index) => {
    const row = document.createElement('tr');
    row.setAttribute('data-id', plan.id);
    row.draggable = true;
    if (selectedPlanId === plan.id) {
      row.classList.add('selected');
    }
    
    // 计算所需番茄钟数量（以分钟字段）
    const requiredSeconds = (plan.minutes || 0) * 60;
    const completedSeconds = (plan.completedPomodoros || 0) * workTime;
    const remainingSeconds = Math.max(0, requiredSeconds - completedSeconds);
    const requiredPomodoros = requiredSeconds > 0 ? Math.ceil(remainingSeconds / workTime) : 0;
    
    row.innerHTML = `
      <td>
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="drag-handle">
          <line x1="8" y1="2" x2="22" y2="2"></line>
          <line x1="8" y1="12" x2="22" y2="12"></line>
          <line x1="8" y1="22" x2="22" y2="22"></line>
          <line x1="2" y1="8" x2="2" y2="8"></line>
          <line x1="2" y1="16" x2="2" y2="16"></line>
        </svg>
      </td>
      <td class="checkbox-cell">
        <input type="checkbox" class="plan-checkbox" data-id="${plan.id}">
      </td>
      <td>${index + 1}</td>
      <td>
        <select class="plan-tag-select" data-id="${plan.id}">
          <option value="">无标签</option>
          ${tags.map(tag => `
            <option value="${tag.id}" ${plan.tagId === tag.id ? 'selected' : ''}>
              ${tag.name}
            </option>
          `).join('')}
        </select>
      </td>
      <td>
        <input type="text" class="plan-title-input" data-id="${plan.id}" value="${plan.title || ''}" placeholder="请输入计划标题（确保计划随着计时而更新）">
      </td>
      <td>
        <div class="time-inputs plan-time">
          <input type="number" class="plan-minutes" data-id="${plan.id}" min="0" value="${plan.minutes || 0}" placeholder="分钟">
        </div>
      </td>
      <td>
        ${plan.completedPomodoros || 0} / ${requiredPomodoros}
      </td>
    `;
    
    planTableBody.appendChild(row);
  });
  
  // 添加事件监听器
  attachPlanEventListeners();
}

// 为计划表格添加事件监听器（仅分钟）
function attachPlanEventListeners() {
  // 计划标题输入
  document.querySelectorAll('.plan-title-input').forEach(input => {
    input.addEventListener('change', function() {
      const planId = this.getAttribute('data-id');
      updatePlanField(planId, 'title', this.value);
    });
  });
  
  // 标签选择
  document.querySelectorAll('.plan-tag-select').forEach(select => {
    select.addEventListener('change', function() {
      const planId = this.getAttribute('data-id');
      updatePlanField(planId, 'tagId', this.value);
    });
  });
  
  // 仅分钟输入
  document.querySelectorAll('.plan-minutes').forEach(input => {
    input.addEventListener('change', function() {
      const planId = this.getAttribute('data-id');
      const value = parseInt(this.value) || 0;
      const clampedValue = Math.max(0, value);
      this.value = clampedValue;
      updatePlanField(planId, 'minutes', clampedValue);
      updatePomodorosDisplay(planId);
    });
  });

  // 计划行选中 — 点击行时选中并聚焦标题输入（对输入/选择/按钮的点击不触发）
  document.querySelectorAll('#plan-table-body tr').forEach(row => {
    row.addEventListener('click', function(e) {
      if (e.target.type === 'checkbox' || e.target.closest('input, select, textarea, button, svg, label')) return;
      
      const planId = this.getAttribute('data-id');
      selectedPlanId = planId;
      renderPlanTable(); // 重新渲染以更新选中状态

      setTimeout(() => {
        const input = document.querySelector(`.plan-title-input[data-id="${planId}"]`);
        if (input) {
          input.focus();
          try {
            const len = input.value.length;
            input.setSelectionRange(len, len);
          } catch (err) {}
        }
      }, 0);
    });
  });
  
  // 复选框点击事件（阻止冒泡，避免触发行选中）
  document.querySelectorAll('.plan-checkbox').forEach(checkbox => {
    checkbox.addEventListener('click', function(e) {
      e.stopPropagation();
      const allCheckboxes = document.querySelectorAll('.plan-checkbox');
      const checkedCheckboxes = document.querySelectorAll('.plan-checkbox:checked');
      selectAllPlansCheckbox.checked = allCheckboxes.length === checkedCheckboxes.length && allCheckboxes.length > 0;
    });
  });
}

// 更新计划字段
function updatePlanField(planId, field, value) {
  const dateKey = getDateKey(currentPlanDate);
  if (!plans[dateKey]) return;
  
  const planIndex = plans[dateKey].findIndex(plan => plan.id === planId);
  if (planIndex !== -1) {
    plans[dateKey][planIndex][field] = value;
    localStorage.setItem('tomatoPlans', JSON.stringify(plans));
  }
}

// 更新番茄钟显示（使用 minutes 字段）
function updatePomodorosDisplay(planId) {
  const dateKey = getDateKey(currentPlanDate);
  if (!plans[dateKey]) return;
  
  const plan = plans[dateKey].find(plan => plan.id === planId);
  if (!plan) return;
  
  // 找到对应的行并更新显示
  const row = document.querySelector(`tr[data-id="${planId}"]`);
  if (row) {
    const requiredSeconds = (plan.minutes || 0) * 60;
    const completedSeconds = (plan.completedPomodoros || 0) * workTime;
    const remainingSeconds = Math.max(0, requiredSeconds - completedSeconds);
    const requiredPomodoros = requiredSeconds > 0 ? Math.ceil(remainingSeconds / workTime) : 0;
    
    const pomodoroCell = row.querySelector('td:last-child');
    pomodoroCell.textContent = `${plan.completedPomodoros || 0} / ${requiredPomodoros}`;
  }
}

// 添加新计划（只保存 minutes）
function addNewPlan(template = null) {
  const dateKey = getDateKey(currentPlanDate);
  if (!plans[dateKey]) {
    plans[dateKey] = [];
  }
  
  const planId = 'plan_' + Date.now();
  
  let newPlan = {
    id: planId,
    title: '',
    tagId: '',
    minutes: 0,
    completedPomodoros: 0
  };
  
  if (template) {
    newPlan.title = template.title;
    newPlan.tagId = template.tagId;
    newPlan.minutes = template.minutes || 0;
  }
  
  plans[dateKey].push(newPlan);
  localStorage.setItem('tomatoPlans', JSON.stringify(plans));
  
  selectedPlanId = planId;
  
  renderPlanTable();
  showNotification('计划已添加', false);

  setTimeout(() => {
    const input = document.querySelector(`.plan-title-input[data-id="${planId}"]`);
    if (input) {
      input.focus();
      try { input.select(); } catch (err) {}
    }
  }, 50);
}

// 删除选中的计划
function deleteSelectedPlans() {
  const dateKey = getDateKey(currentPlanDate);
  if (!plans[dateKey]) return;
  
  const checkedIds = Array.from(document.querySelectorAll('.plan-checkbox:checked'))
    .map(checkbox => checkbox.getAttribute('data-id'));
  
  if (checkedIds.includes(selectedPlanId)) {
    selectedPlanId = null;
  }
  
  plans[dateKey] = plans[dateKey].filter(plan => !checkedIds.includes(plan.id));
  
  localStorage.setItem('tomatoPlans', JSON.stringify(plans));
  renderPlanTable();
  
  selectAllPlansCheckbox.checked = false;
  
  showNotification(`已删除 ${checkedIds.length} 个计划`, false);
}

// 渲染标签管理界面
function renderTagManagement() {
  tagManagementContainer.innerHTML = '';
  
  tags.forEach(tag => {
    const tagItem = document.createElement('div');
    tagItem.className = 'tag-item';
    tagItem.setAttribute('data-id', tag.id);
    
    tagItem.innerHTML = `
      <div class="tag-info">
        <input type="color" class="tag-color-picker" value="${tag.color}" data-id="${tag.id}">
        <input type="text" class="tag-name-input" value="${tag.name}" data-id="${tag.id}" placeholder="标签名称">
      </div>
      <button class="delete-btn delete-tag-btn" data-id="${tag.id}">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <line x1="18" y1="6" x2="6" y2="18"></line>
          <line x1="6" y1="6" x2="18" y2="18"></line>
        </svg>
      </button>
    `;
    
    tagManagementContainer.appendChild(tagItem);
  });
  
  document.querySelectorAll('.delete-tag-btn').forEach(btn => {
    btn.addEventListener('click', function() {
      const tagId = this.getAttribute('data-id');
      tags = tags.filter(tag => tag.id !== tagId);
      renderTagManagement();
    });
  });
  
  document.querySelectorAll('.tag-color-picker').forEach(picker => {
    picker.addEventListener('input', function() {
      const tagId = this.getAttribute('data-id');
      const tag = tags.find(t => t.id === tagId);
      if (tag) {
        tag.color = this.value;
      }
    });
  });
  
  document.querySelectorAll('.tag-name-input').forEach(input => {
    input.addEventListener('change', function() {
      const tagId = this.getAttribute('data-id');
      const tag = tags.find(t => t.id === tagId);
      if (tag) {
        tag.name = this.value;
      }
    });
  });
}

// 添加新标签
function addNewTag() {
  const newTag = {
    id: 'tag_' + Date.now(),
    name: '新标签',
    color: '#4a6fa5' // 默认颜色
  };
  
  tags.push(newTag);
  renderTagManagement();
  
  setTimeout(() => {
    const newInput = document.querySelector(`.tag-name-input[data-id="${newTag.id}"]`);
    if (newInput) {
      newInput.focus();
      newInput.select();
    }
  }, 100);
}

// 保存标签管理
function saveTagManagement() {
  document.querySelectorAll('.tag-item').forEach(item => {
    const tagId = item.getAttribute('data-id');
    const tag = tags.find(t => t.id === tagId);
    if (tag) {
      const nameInput = item.querySelector('.tag-name-input');
      const colorPicker = item.querySelector('.tag-color-picker');
      tag.name = nameInput.value;
      tag.color = colorPicker.value;
    }
  });
  
  tags = tags.filter(tag => tag.name.trim() !== '');
  localStorage.setItem('tomatoTags', JSON.stringify(tags));
}

// 渲染模板选择器（仅分钟显示）
function renderTemplateSelector() {
  templateSelector.innerHTML = '';
  
  if (templates.length === 0) {
    templateSelector.innerHTML = '<p style="text-align: center; padding: 10px;">暂无模板，请先添加模板</p>';
    return;
  }
  
  templates.forEach(template => {
    const templateItem = document.createElement('div');
    templateItem.className = 'template-select-item';
    templateItem.setAttribute('data-id', template.id);
    
    const tag = tags.find(t => t.id === template.tagId);
    const tagHtml = tag ? `<span class="tag-color-indicator" style="background-color: ${tag.color};"></span>${tag.name}` : '无标签';
    
    templateItem.innerHTML = `
      <strong>${template.title}</strong>
      <div style="font-size: 0.9rem; color: var(--gray);">
        ${tagHtml} · ${template.minutes || 0} 分
      </div>
    `;
    
    templateItem.addEventListener('click', function() {
      const templateId = this.getAttribute('data-id');
      const selectedTemplate = templates.find(t => t.id === templateId);
      if (selectedTemplate) {
        addNewPlan(selectedTemplate);
        addPlanModal.style.display = 'none';
      }
    });
    
    templateSelector.appendChild(templateItem);
  });
}

// 渲染模板管理界面（仅分钟）
function renderTemplateManagement() {
  templateManagementContainer.innerHTML = '';
  
  templates.forEach(template => {
    const templateItem = document.createElement('div');
    templateItem.className = 'template-item';
    templateItem.setAttribute('data-id', template.id);
    
    templateItem.innerHTML = `
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <h4>模板 ${templates.indexOf(template) + 1}</h4>
        <button class="delete-btn delete-template-btn" data-id="${template.id}">删除</button>
      </div>
      <div class="template-fields">
        <input type="text" class="template-title-input" data-id="${template.id}" value="${template.title || ''}" placeholder="计划标题（必填）">
        <select class="template-tag-select" data-id="${template.id}">
          <option value="">无标签</option>
          ${tags.map(tag => `<option value="${tag.id}" ${template.tagId === tag.id ? 'selected' : ''}>${tag.name}</option>`).join('')}
        </select>
        <div class="time-inputs plan-time">
          <input type="number" class="template-minutes" data-id="${template.id}" min="0" value="${template.minutes || 0}" placeholder="分钟">
        </div>
      </div>
    `;
    
    templateManagementContainer.appendChild(templateItem);
  });
  
  document.querySelectorAll('.delete-template-btn').forEach(btn => {
    btn.addEventListener('click', function() {
      const templateId = this.getAttribute('data-id');
      templates = templates.filter(template => template.id !== templateId);
      renderTemplateManagement();
    });
  });
  
  document.querySelectorAll('.template-title-input').forEach(input => {
    input.addEventListener('change', function() {
      const templateId = this.getAttribute('data-id');
      const template = templates.find(t => t.id === templateId);
      if (template) template.title = this.value;
    });
  });
  
  document.querySelectorAll('.template-tag-select').forEach(select => {
    select.addEventListener('change', function() {
      const templateId = this.getAttribute('data-id');
      const template = templates.find(t => t.id === templateId);
      if (template) template.tagId = this.value;
    });
  });
  
  document.querySelectorAll('.template-minutes').forEach(input => {
    input.addEventListener('change', function() {
      const templateId = this.getAttribute('data-id');
      const template = templates.find(t => t.id === templateId);
      if (template) template.minutes = parseInt(this.value) || 0;
    });
  });
}

// 添加新模板（分钟）
function addNewTemplate() {
  const newTemplate = {
    id: 'template_' + Date.now(),
    title: '',
    tagId: '',
    minutes: 0
  };
  
  templates.push(newTemplate);
  renderTemplateManagement();
  
  setTimeout(() => {
    const newInput = document.querySelector(`.template-title-input[data-id="${newTemplate.id}"]`);
    if (newInput) newInput.focus();
  }, 100);
}

// 保存模板管理（只保存分钟）
function saveTemplateManagement() {
  document.querySelectorAll('.template-item').forEach(item => {
    const templateId = item.getAttribute('data-id');
    const template = templates.find(t => t.id === templateId);
    if (template) {
      const titleInput = item.querySelector('.template-title-input');
      const tagSelect = item.querySelector('.template-tag-select');
      const minutesInput = item.querySelector('.template-minutes');
      template.title = titleInput.value;
      template.tagId = tagSelect.value;
      template.minutes = parseInt(minutesInput.value) || 0;
    }
  });
  
  templates = templates.filter(t => t.title && t.title.trim() !== '');
  localStorage.setItem('tomatoTemplates', JSON.stringify(templates));
}

// 获取日期键（YYYY-MM-DD）
function getDateKey(date) {
  return date.toISOString().split('T')[0];
}

// 当工作周期完成时，更新选中计划的番茄钟计数
function updateSelectedPlanPomodoros() {
  if (!selectedPlanId) return;
  
  const dateKey = getDateKey(currentPlanDate);
  if (!plans[dateKey]) return;
  
  const planIndex = plans[dateKey].findIndex(plan => plan.id === selectedPlanId);
  if (planIndex === -1) return;
  
  const plan = plans[dateKey][planIndex];
  
  // 检查计划是否有效（有标题和所需时间）
  if (!plan.title || (!plan.minutes && plan.minutes !== 0 && plan.minutes !== 0)) {
    return;
  }
  
  // 增加已完成番茄钟计数
  plan.completedPomodoros = (plan.completedPomodoros || 0) + 1;
  localStorage.setItem('tomatoPlans', JSON.stringify(plans));
  
  // 更新计划表格显示
  renderPlanTable();
}

// 导出所有数据（包括计划、标签和模板）
function exportAllData() {
  const exportData = {
    records: records,
    plans: plans,
    tags: tags,
    templates: templates,
    settings: {
      workTime: workTime,
      restTime: restTime,
      enableNotifications: enableNotifications,
      notificationSound: notificationSound
    },
    exportDate: new Date().toISOString()
  };
  
  const jsonString = JSON.stringify(exportData, null, 2);
  const blob = new Blob([jsonString], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  
  const a = document.createElement('a');
  a.href = url;
  const dateStr = new Date().toISOString().split('T')[0];
  a.download = `番茄钟数据_${dateStr}.json`;
  document.body.appendChild(a);
  a.click();
  setTimeout(() => {
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }, 0);
  
  showNotification('数据已导出', false);
}

// 处理文件导入（包括计划、标签和模板）
function handleFileImport(event) {
  const file = event.target.files[0];
  if (!file) return;
  
  if (file.type !== 'application/json' && !file.name.endsWith('.json')) {
    showNotification('请导入JSON格式文件', false);
    fileInput.value = '';
    return;
  }
  
  const reader = new FileReader();
  reader.onload = function(e) {
    try {
      const data = JSON.parse(e.target.result);
      if (!data.records || !Array.isArray(data.records)) {
        throw new Error('数据格式不正确');
      }
      importData = data;
      showImportConfirmation();
    } catch (error) {
      showNotification(`导入失败: ${error.message}`, false);
      console.error('导入错误:', error);
    }
  };
  
  reader.onerror = function() {
    showNotification('文件读取失败', false);
  };
  
  reader.readAsText(file);
  fileInput.value = '';
}

// 显示导入确认对话框
function showImportConfirmation() {
  importConfirmModal.style.display = 'flex';
}

// 隐藏导入确认对话框
function hideImportConfirmation() {
  importConfirmModal.style.display = 'none';
  importData = null;
}

// 确认导入数据（包括计划、标签和模板）
function confirmDataImport() {
  if (!importData) {
    hideImportConfirmation();
    return;
  }
  
  try {
    records = importData.records || [];
    localStorage.setItem('tomatoRecords', JSON.stringify(records));
    
    if (importData.plans) {
      plans = importData.plans;
      localStorage.setItem('tomatoPlans', JSON.stringify(plans));
    }
    if (importData.tags) {
      tags = importData.tags;
      localStorage.setItem('tomatoTags', JSON.stringify(tags));
    }
    if (importData.templates) {
      templates = importData.templates;
      localStorage.setItem('tomatoTemplates', JSON.stringify(templates));
    }
    
    if (importData.settings) {
      if (importData.settings.workTime !== undefined) {
        workTime = importData.settings.workTime;
        const workMinutes = Math.floor(workTime / 60);
        workMinutesInput.value = workMinutes;
      }
      if (importData.settings.restTime !== undefined) {
        restTime = importData.settings.restTime;
        const restMinutes = Math.floor(restTime / 60);
        restMinutesInput.value = restMinutes;
      }
      if (importData.settings.enableNotifications !== undefined) {
        enableNotifications = importData.settings.enableNotifications;
        enableNotificationsInput.checked = enableNotifications;
      }
      if (importData.settings.notificationSound !== undefined) {
        notificationSound = importData.settings.notificationSound;
        notificationSoundInput.checked = notificationSound;
      }
      
      localStorage.setItem('tomatoSettings', JSON.stringify({
        workTime: workTime,
        restTime: restTime,
        enableNotifications: enableNotifications,
        notificationSound: notificationSound
      }));
      
      if (currentState === STATES.IDLE) {
        remainingTime = workTime;
        updateDisplay();
      }
    }
    
    renderPlanTable();
    renderTagManagement();
    renderTemplateManagement();
    renderTemplateSelector();
    
    showNotification('数据导入成功', false);
    updateDataDisplay();
  } catch (error) {
    showNotification(`导入失败: ${error.message}`, false);
    console.error('导入错误:', error);
  }
  
  hideImportConfirmation();
}

// 加载保存的设置（仅分钟输入）
function loadSettings() {
  const savedSettings = JSON.parse(localStorage.getItem('tomatoSettings') || '{}');
  if (savedSettings.workTime !== undefined) {
    workTime = savedSettings.workTime;
    const workMinutes = Math.floor(workTime / 60);
    workMinutesInput.value = workMinutes;
  }
  if (savedSettings.restTime !== undefined) {
    restTime = savedSettings.restTime;
    const restMinutes = Math.floor(restTime / 60);
    restMinutesInput.value = restMinutes;
  }
  
  enableNotifications = savedSettings.enableNotifications !== undefined ? savedSettings.enableNotifications : true;
  notificationSound = savedSettings.notificationSound !== undefined ? savedSettings.notificationSound : true;
  
  enableNotificationsInput.checked = enableNotifications;
  notificationSoundInput.checked = notificationSound;
  
  remainingTime = workTime;
}

// 保存设置
function saveSettings() {
  const workMinutes = parseInt(workMinutesInput.value) || 0;
  const restMinutes = parseInt(restMinutesInput.value) || 0;
  
  if (isNaN(workMinutes) || workMinutes <= 0) {
    showNotification('工作分钟需大于0', false);
    return;
  }
  if (isNaN(restMinutes) || restMinutes <= 0) {
    showNotification('休息分钟需大于0', false);
    return;
  }
  
  enableNotifications = enableNotificationsInput.checked;
  notificationSound = notificationSoundInput.checked;
  
  workTime = workMinutes * 60;
  restTime = restMinutes * 60;
  
  localStorage.setItem('tomatoSettings', JSON.stringify({
    workTime, restTime, enableNotifications, notificationSound
  }));
  
  if (currentState === STATES.IDLE) {
    remainingTime = workTime;
    updateDisplay();
  }
  
  renderPlanTable();
  showNotification('设置已保存', false);
  switchToInterface('timer-interface');
}

// 切换到指定界面
function switchToInterface(interfaceId) {
  navItems.forEach(nav => nav.classList.remove('active'));
  document.querySelector(`.nav-item[data-target="${interfaceId}"]`).classList.add('active');
  
  interfaces.forEach(iface => iface.classList.remove('active'));
  document.getElementById(interfaceId).classList.add('active');
}

// 显示清除确认对话框
function showClearConfirmation() {
  updateClearConfirmationMessage();
  confirmModal.style.display = 'flex';
}

// 更新清除确认消息
function updateClearConfirmationMessage() {
  const periodNames = {
    'day': '当天',
    'week': '当周',
    'month': '当月',
    'year': '当年'
  };
  
  const options = { year: 'numeric', month: 'long', day: 'numeric' };
  const formattedDate = selectedDate.toLocaleDateString('zh-CN', options);
  
  const selectedScope = document.querySelector('input[name="clearScope"]:checked').value;
  
  if (selectedScope === 'current') {
    confirmMessageEl.textContent = `确定清除${periodNames[currentPeriod]}（${formattedDate}）的数据？不可恢复。`;
  } else {
    confirmMessageEl.textContent = '确定清除所有数据？不可恢复。';
  }
}

// 隐藏清除确认对话框
function hideClearConfirmation() {
  confirmModal.style.display = 'none';
}

// 清除选中范围的数据
function clearSelectedData() {
  const selectedScope = document.querySelector('input[name="clearScope"]:checked').value;
  
  if (selectedScope === 'current') {
    const { startDate, endDate } = getPeriodDateRange(currentPeriod, selectedDate);
    records = records.filter(record => {
      const recordDate = new Date(record.timestamp);
      return !(recordDate >= startDate && recordDate < endDate);
    });
    showNotification('当前周期数据已清除', false);
  } else {
    records = [];
    showNotification('所有数据已清除', false);
  }
  
  localStorage.setItem('tomatoRecords', JSON.stringify(records));
  hideClearConfirmation();
  updateDataDisplay();
}

// 获取周期的日期范围
function getPeriodDateRange(period, baseDate) {
  let startDate, endDate;
  const date = new Date(baseDate);
  
  switch (period) {
    case 'day':
      startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
      endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
      break;
    case 'week':
      const dayOfWeek = date.getDay() || 7;
      const diffToMonday = dayOfWeek - 1;
      startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - diffToMonday);
      endDate = new Date(startDate);
      endDate.setDate(endDate.getDate() + 7);
      break;
    case 'month':
      startDate = new Date(date.getFullYear(), date.getMonth(), 1);
      endDate = new Date(date.getFullYear(), date.getMonth() + 1, 1);
      break;
    case 'year':
      startDate = new Date(date.getFullYear(), 0, 1);
      endDate = new Date(date.getFullYear() + 1, 0, 1);
      break;
    default:
      startDate = new Date(0);
      endDate = new Date();
  }
  
  return { startDate, endDate };
}

// 导航到上一周期或下一周期
function navigatePeriod(direction) {
  const newDate = new Date(selectedDate);
  
  switch(currentPeriod) {
    case 'day':
      newDate.setDate(newDate.getDate() + direction);
      break;
    case 'week':
      newDate.setDate(newDate.getDate() + (direction * 7));
      break;
    case 'month':
      newDate.setMonth(newDate.getMonth() + direction);
      break;
    case 'year':
      newDate.setFullYear(newDate.getFullYear() + direction);
      break;
  }
  
  selectedDate = newDate;
  datePicker.value = selectedDate.toISOString().split('T')[0];
  updateDataDisplay();
}

// 请求通知权限（保留调试信息）
function checkNotificationSupport() {
  console.log('=== 通知API检测 ===');
  console.log('浏览器是否支持Notification:', 'Notification' in window);
  if (!('Notification' in window)) {
    console.error('原因：浏览器不支持或禁用了Notification API');
    return;
  }
  console.log('检测完成：环境支持Notification API');
}

function requestNotificationPermission() {
  checkNotificationSupport();
  if ('Notification' in window) {
    Notification.requestPermission().then((permission) => {
      if (permission === 'granted') {
        showNotification('已授予通知权限', false);
      } else if (permission === 'denied') {
        showNotification('通知权限已被拒绝，请在浏览器设置中启用', false);
      } else if (permission === 'default') {
        showNotification('权限可能被浏览器屏蔽', false);
      }
    });
  } else {
    console.log('浏览器不支持系统通知');
  }
}

// 显示通知
function showNotification(message, system) {
  notification.textContent = message;
  notification.style.display = 'block';
  setTimeout(() => {
    notification.style.display = 'none';
  }, 5000);

  if (enableNotifications && 'Notification' in window && window.Notification.permission === 'granted' && system === true) {
    new Notification('番茄钟', {
      body: message,
      icon: '/favicon.ico',
      sound: notificationSound,
      requireInteraction: false,
    });
  }
}

// 更新显示
function updateDisplay() {
  const minutes = Math.floor(remainingTime / 60);
  const seconds = remainingTime % 60;
  timerDisplay.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  
  const statusTexts = {
    [STATES.IDLE]: '未启动',
    [STATES.WORKING]: '工作中',
    [STATES.WORK_END]: '工作结束',
    [STATES.SOLVED]: '解决',
    [STATES.RESTING]: '休息中',
    [STATES.PAUSED]: '暂停'
  };
  statusDisplay.textContent = statusTexts[currentState];
  
  updateButtons();
}

// 更新按钮
function updateButtons() {
  buttonsContainer.innerHTML = '';
  
  switch (currentState) {
    case STATES.IDLE:
      buttonsContainer.appendChild(createButton('开始工作', 'btn-primary', startWorking));
      break;
    case STATES.WORKING:
      buttonsContainer.appendChild(createButton('暂停', 'btn-warning', pauseTimer));
      buttonsContainer.appendChild(createButton('停止', 'btn-danger', stopTimer));
      break;
    case STATES.WORK_END:
      buttonsContainer.appendChild(createButton('休息', 'btn-success', startRest));
      buttonsContainer.appendChild(createButton('解决', 'btn-warning', interrupt));
      buttonsContainer.appendChild(createButton('停止', 'btn-danger', stopTimer));
      break;
    case STATES.SOLVED:
      buttonsContainer.appendChild(createButton('休息', 'btn-success', startRest));
      buttonsContainer.appendChild(createButton('停止', 'btn-danger', stopTimer));
      break;
    case STATES.RESTING:
      buttonsContainer.appendChild(createButton('暂停', 'btn-warning', pauseTimer));
      buttonsContainer.appendChild(createButton('停止', 'btn-danger', stopTimer));
      break;
    case STATES.PAUSED:
      buttonsContainer.appendChild(createButton('继续', 'btn-primary', continueTimer));
      buttonsContainer.appendChild(createButton('停止', 'btn-danger', stopTimer));
      break;
  }
}

// 创建按钮（保留简单文本）
function createButton(text, className, onClick) {
  const button = document.createElement('button');
  button.textContent = text;
  button.className = className;
  button.addEventListener('click', onClick);
  return button;
}

// 开始工作
function startWorking() {
  currentState = STATES.WORKING;
  remainingTime = workTime;
  startTime = new Date();
  totalPauseTime = 0;
  recordStateChange(STATES.WORKING);
  startTimer();
  updateDisplay();
}

// 开始休息
function startRest() {
  currentState = STATES.RESTING;
  remainingTime = restTime;
  startTime = new Date();
  totalPauseTime = 0;
  recordStateChange(STATES.RESTING);
  startTimer();
  updateDisplay();
}

// 中断（进入解决状态）
function interrupt() {
  currentState = STATES.SOLVED;
  recordStateChange(STATES.SOLVED);
  updateDisplay();
}

function pauseTimer() {
  if (currentState === STATES.WORKING || currentState === STATES.RESTING) {
    backState = currentState;
    currentState = STATES.PAUSED;
    pauseStartTime = new Date();

    if (startTime != null && initialRemaining !== undefined) {
      const elapsedSeconds = Math.floor((Date.now() - startTime) / 1000);
      remainingTime = Math.max(0, initialRemaining - elapsedSeconds);
    }

    if (animationId) {
      cancelAnimationFrame(animationId);
      animationId = null;
    }
    if (endTimeoutId) {
      clearTimeout(endTimeoutId);
      endTimeoutId = null;
    }

    recordStateChange(STATES.PAUSED);
    updateDisplay();
  }
}

function continueTimer() {
  if (currentState === STATES.PAUSED) {
    currentState = backState;
    if (pauseStartTime) {
      const pauseDuration = (new Date() - pauseStartTime) / 1000;
      totalPauseTime += pauseDuration;
      pauseStartTime = null;
    }
    recordStateChange(currentState);
    startTimer();
    updateDisplay();
  }
}

function stopTimer() {
  if (animationId) {
    cancelAnimationFrame(animationId);
    animationId = null;
  }
  if (endTimeoutId) {
    clearTimeout(endTimeoutId);
    endTimeoutId = null;
  }

  currentState = STATES.IDLE;
  remainingTime = workTime;
  startTime = null;
  pauseStartTime = null;
  totalPauseTime = 0;
  initialRemaining = undefined;

  recordStateChange(STATES.IDLE);
  updateDisplay();
}

// 启动计时器（保持现有稳定实现）
function startTimer() {
  if (animationId) {
    cancelAnimationFrame(animationId);
    animationId = null;
  }
  if (endTimeoutId) {
    clearTimeout(endTimeoutId);
    endTimeoutId = null;
  }

  startTime = Date.now();
  initialRemaining = remainingTime;
  targetTime = startTime + remainingTime * 1000;

  let lastElapsedSeconds = -1;

  function updateTimer() {
    const elapsedMs = Date.now() - startTime;
    const elapsedSeconds = Math.floor(elapsedMs / 1000);
    const newRemaining = initialRemaining - elapsedSeconds;

    if (elapsedSeconds !== lastElapsedSeconds) {
      remainingTime = Math.max(0, newRemaining);
      updateDisplay();
      lastElapsedSeconds = elapsedSeconds;
    }

    if (remainingTime <= 0) {
      finishTimer();
      return;
    }

    animationId = requestAnimationFrame(updateTimer);
  }

  endTimeoutId = setTimeout(() => {
    if (animationId) {
      cancelAnimationFrame(animationId);
      animationId = null;
    }
    endTimeoutId = null;
    finishTimer();
  }, Math.max(0, targetTime - Date.now()));

  animationId = requestAnimationFrame(updateTimer);
}

function finishTimer() {
  if (animationId) {
    cancelAnimationFrame(animationId);
    animationId = null;
  }
  if (endTimeoutId) {
    clearTimeout(endTimeoutId);
    endTimeoutId = null;
  }

  remainingTime = 0;

  if (currentState === STATES.WORKING) {
    currentState = STATES.WORK_END;
    showNotification('工作计时结束！', true);
    updateSelectedPlanPomodoros();
  } else if (currentState === STATES.RESTING) {
    currentState = STATES.IDLE;
    showNotification('休息计时结束！', true);
  }

  recordStateChange(currentState);
  updateDisplay();
}

// 记录状态变化
function recordStateChange(state) {
  const record = {
    timestamp: new Date(),
    state: state
  };
  
  records.push(record);
  localStorage.setItem('tomatoRecords', JSON.stringify(records));
}

// 更新数据展示（单位：分钟）
function updateDataDisplay() {
  const { startDate, endDate } = getPeriodDateRange(currentPeriod, selectedDate);
  const filteredRecords = records.filter(record => {
    const recordDate = new Date(record.timestamp);
    return recordDate >= startDate && recordDate < endDate;
  });
  
  const stats = calculateStats(filteredRecords, currentPeriod);
  
  workSessionsEl.textContent = stats.workSessions;
  totalWorkEl.textContent = formatTime(stats.totalWork);
  totalRestEl.textContent = formatTime(stats.totalRest);
  totalSolveEl.textContent = formatTime(stats.totalSolve);
  
  if (currentPeriod === 'day') {
    renderDayChart(filteredRecords);
  } else {
    renderPeriodChart(filteredRecords, currentPeriod, startDate, endDate);
  }
}

// 计算统计数据（返回的是分钟）
function calculateStats(records, period) {
  let workSessions = 0;
  let totalWork = 0;
  let totalRest = 0;
  let totalSolve = 0;
  const dateGroups = {};
  
  for (let i = 0; i < records.length - 1; i++) {
    const current = records[i];
    const next = records[i + 1];
    const durationMinutes = (new Date(next.timestamp) - new Date(current.timestamp)) / 60000.0;
    
    if (current.state === STATES.WORKING) {
      totalWork += durationMinutes;
    } else if (current.state === STATES.RESTING) {
      totalRest += durationMinutes;
    } else if (current.state === STATES.SOLVED) {
      totalSolve += durationMinutes;
    }
    
    if (current.state === STATES.WORKING) {
      const date = new Date(current.timestamp).toDateString();
      if (!dateGroups[date]) dateGroups[date] = new Set();
      dateGroups[date].add(current.timestamp);
    }
  }
  
  for (const date in dateGroups) {
    workSessions += dateGroups[date].size;
  }
  
  return {
    workSessions,
    totalWork,
    totalRest,
    totalSolve
  };
}

// 分组统计（返回 minutes）
function calculateGroupedStats(records, period, startDate, endDate) {
  const groups = {};
  const groupKeys = [];
  let current = new Date(startDate);
  
  while (current < endDate) {
    let key, next;
    if (period === 'week' || period === 'month') {
      key = current.toDateString();
      next = new Date(current);
      next.setDate(next.getDate() + 1);
      groupKeys.push({ key: key, label: `${current.getMonth() + 1}/${current.getDate()}` });
    } else if (period === 'year') {
      key = `${current.getFullYear()}-${current.getMonth() + 1}`;
      next = new Date(current.getFullYear(), current.getMonth() + 1, 1);
      groupKeys.push({ key: key, label: `${current.getMonth() + 1}月` });
    }
    groups[key] = { workSessions: 0, totalWork: 0, totalRest: 0, totalSolve: 0, workTimestamps: new Set() };
    current = next;
  }
  
  for (let i = 0; i < records.length - 1; i++) {
    const currentRecord = records[i];
    const nextRecord = records[i + 1];
    const recordDate = new Date(currentRecord.timestamp);
    let key;
    if (period === 'week' || period === 'month') key = recordDate.toDateString();
    else if (period === 'year') key = `${recordDate.getFullYear()}-${recordDate.getMonth() + 1}`;
    if (!groups[key]) continue;
    const durationMinutes = (new Date(nextRecord.timestamp) - new Date(currentRecord.timestamp)) / 60000.0;
    if (currentRecord.state === STATES.WORKING) {
      groups[key].totalWork += durationMinutes;
      groups[key].workTimestamps.add(currentRecord.timestamp);
    } else if (currentRecord.state === STATES.RESTING) {
      groups[key].totalRest += durationMinutes;
    } else if (currentRecord.state === STATES.SOLVED) {
      groups[key].totalSolve += durationMinutes;
    }
  }
  
  groupKeys.forEach(item => {
    groups[item.key].workSessions = groups[item.key].workTimestamps.size;
  });
  
  return { groups, groupKeys };
}

// 格式化时间（输入单位：分钟，输出以分钟为主）
function formatTime(minutes) {
  if (minutes >= 1) {
    const rounded = Math.round(minutes * 10) / 10;
    return Number.isInteger(rounded) ? `${rounded}分` : `${rounded.toFixed(1)}分`;
  } else {
    const seconds = Math.round(minutes * 60);
    return `${seconds}秒`;
  }
}

// 渲染日视图图表（单位：分钟）
function renderDayChart(records) {
  if (window.timeChart) {
    window.timeChart.destroy();
  }
  
  const ctx = timeChartCanvas.getContext('2d');
  const labels = [];
  const datasets = [
    { label: '工作', data: [], backgroundColor: 'rgba(52,152,219,0.5)', borderColor: 'rgba(52,152,219,1)', borderWidth: 1 },
    { label: '休息', data: [], backgroundColor: 'rgba(46,204,113,0.5)', borderColor: 'rgba(46,204,113,1)', borderWidth: 1 },
    { label: '解决', data: [], backgroundColor: 'rgba(231,76,60,0.5)', borderColor: 'rgba(231,76,60,1)', borderWidth: 1 }
  ];
  
  for (let i = 0; i < 24; i++) {
    labels.push(`${i.toString().padStart(2,'0')}:00`);
    datasets.forEach(ds => ds.data.push(0.0));
  }
  
  for (let i = 0; i < records.length - 1; i++) {
    const current = records[i];
    const next = records[i + 1];
    const start = new Date(current.timestamp);
    const end = new Date(next.timestamp);
    const startHour = start.getHours();
    const endHour = end.getHours();
    const durationMinutes = (end - start) / 60000.0;
    
    let datasetIndex = -1;
    if (current.state === STATES.WORKING) datasetIndex = 0;
    else if (current.state === STATES.RESTING) datasetIndex = 1;
    else if (current.state === STATES.SOLVED) datasetIndex = 2;
    if (datasetIndex === -1) continue;
    
    if (startHour === endHour) {
      datasets[datasetIndex].data[startHour] += durationMinutes;
    } else {
      const minutesLeftInStartHour = 60 - start.getMinutes() - start.getSeconds() / 60;
      const minutesInEndHour = end.getMinutes() + end.getSeconds() / 60;
      datasets[datasetIndex].data[startHour] += Math.max(0, minutesLeftInStartHour);
      if (endHour < 24) datasets[datasetIndex].data[endHour] += Math.max(0, minutesInEndHour);
      // 中间整小时
      for (let h = startHour + 1; h < endHour; h++) {
        if (h < 24) datasets[datasetIndex].data[h] += 60;
      }
      // 如果 span crosses midnight or different days, small inaccuracies acceptable in minute-aggregation
    }
  }
  
  window.timeChart = new Chart(ctx, {
    type: 'bar',
    data: { labels, datasets },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        x: { title: { display: true, text: '时间' } },
        y: { beginAtZero: true, title: { display: true, text: '时长 (分钟)' } }
      },
      plugins: {
        legend: { position: 'top' },
        title: { display: true, text: '一天中的活动分布（分钟）' }
      }
    }
  });
}

// 渲染周/月/年视图（单位：分钟）
function renderPeriodChart(records, period, startDate, endDate) {
  if (window.timeChart) {
    window.timeChart.destroy();
  }
  
  const ctx = timeChartCanvas.getContext('2d');
  const { groups, groupKeys } = calculateGroupedStats(records, period, startDate, endDate);
  
  const labels = groupKeys.map(item => item.label);
  const workSessionsData = groupKeys.map(item => groups[item.key].workSessions);
  const workTimeData = groupKeys.map(item => groups[item.key].totalWork);
  const restTimeData = groupKeys.map(item => groups[item.key].totalRest);
  const solveTimeData = groupKeys.map(item => groups[item.key].totalSolve);
  
  const titles = { 'week': '一周活动趋势', 'month': '一月活动趋势', 'year': '一年活动趋势' };
  
  window.timeChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [
        { label: '工作次数', data: workSessionsData, borderColor: 'rgba(155,89,182,1)', backgroundColor: 'rgba(155,89,182,0.1)', borderWidth: 2, fill: false, tension: 0.1, yAxisID: 'y' },
        { label: '工作时长(分钟)', data: workTimeData, borderColor: 'rgba(52,152,219,1)', backgroundColor: 'rgba(52,152,219,0.1)', borderWidth: 2, fill: false, tension: 0.1, yAxisID: 'y1' },
        { label: '休息时长(分钟)', data: restTimeData, borderColor: 'rgba(46,204,113,1)', backgroundColor: 'rgba(46,204,113,0.1)', borderWidth: 2, fill: false, tension: 0.1, yAxisID: 'y1' },
        { label: '解决时长(分钟)', data: solveTimeData, borderColor: 'rgba(231,76,60,1)', backgroundColor: 'rgba(231,76,60,0.1)', borderWidth: 2, fill: false, tension: 0.1, yAxisID: 'y1' }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: { mode: 'index', intersect: false },
      scales: {
        x: { title: { display: true, text: period === 'year' ? '月份' : '日期' } },
        y: { type: 'linear', display: true, position: 'left', title: { display: true, text: '次数' }, beginAtZero: true },
        y1: { type: 'linear', display: true, position: 'right', title: { display: true, text: '时长(分钟)' }, beginAtZero: true, grid: { drawOnChartArea: false } }
      },
      plugins: { legend: { position: 'top' }, title: { display: true, text: titles[period] } }
    }
  });
}

// 初始化应用
init();